CODE 25. Convert Sorted Array to Binary Search Tree

版权声明:本文为博主原创文章,转载请注明出处,谢谢!

版权声明:本文为博主原创文章,转载请注明出处:http://blog.jerkybible.com/2013/09/20/2013-09-20-CODE 25 Convert Sorted Array to Binary Search Tree/

访问原文「CODE 25. Convert Sorted Array to Binary Search Tree

Given an array where elements are sorted in ascending order, convert it to a height balanced BST.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public TreeNode sortedArrayToBST(int[] num) {
// Start typing your Java solution below
// DO NOT write main() function
if (num == null || num.length <= 0) {
return null;
}
return dfs(num, 0, num.length - 1);
}
TreeNode dfs(int[] num, int min, int max) {
TreeNode node = null;
if (min <= max) {
int mid = (max + min) / 2;
node = new TreeNode(num[mid]);
TreeNode left = dfs(num, min, mid - 1);
TreeNode right = dfs(num, mid + 1, max);
node.left = left;
node.right = right;
}
return node;
}
Jerky Lu wechat
欢迎加入微信公众号